<template>
  <div class="user-profile-container">
    <el-container>
      <el-aside width="200px" class="profile-aside">
        <el-menu
            :default-active="activeTab"
            class="el-menu-vertical-demo"
            @select="handleMenuSelect"
        >
          <el-menu-item index="myCourses">
            <el-icon><Reading /></el-icon>
            <span>我的课程</span>
          </el-menu-item>
          <el-menu-item index="myCollections">
            <el-icon><Star /></el-icon>
            <span>我的收藏</span>
          </el-menu-item>
          <el-menu-item index="myOrders">
            <el-icon><Tickets /></el-icon>
            <span>我的订单</span>
          </el-menu-item>
          <el-menu-item index="userInfo">
            <el-icon><User /></el-icon>
            <span>个人信息</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main class="profile-main">
        <div v-if="activeTab === 'userInfo'">
          <el-descriptions
              class="margin-top"
              title="个人信息"
              :column="2"
              border
          >
            <template #extra>
              <!-- <el-button type="primary" size="small">编辑</el-button> -->
            </template>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon><User /></el-icon>
                  用户名
                </div>
              </template>
              {{ userStore.userInfo.name }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon><Message /></el-icon>
                  邮箱
                </div>
              </template>
              {{ userStore.userInfo.email }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon><Stamp /></el-icon>
                  用户类型
                </div>
              </template>
              <el-tag :type="Number(userStore.userInfo.isVIP) === 1 ? 'success' : 'info'">
                {{ Number(userStore.userInfo.isVIP) === 1 ? 'VIP用户' : '普通用户' }}
              </el-tag>
              <el-button
                  v-if="Number(userStore.userInfo.isVIP) !== 1"
                  type="warning"
                  size="small"
                  plain
                  style="margin-left: 10px;"
                  @click="openVipDialog"
              >
                VIP服务
              </el-button>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon><Lock /></el-icon>
                  账户状态
                </div>
              </template>
              <el-tag :type="userStore.userInfo.isFrozen === 1 ? 'danger' : 'success'">
                {{ userStore.userInfo.isFrozen === 1 ? '已冻结' : '正常' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>

          <!-- VIP购买弹窗 -->
          <el-dialog
              v-model="showVipDialog"
              title="VIP会员服务"
              width="60%"
              center
              align-center
              destroy-on-close
              :close-on-click-modal="false"
          >
            <div class="vip-products-container-dialog">
              <div class="vip-header">
                <h2>选择您的VIP套餐</h2>
                <p class="vip-subtitle">升级VIP会员，享受更多特权</p>
              </div>
              <div class="product-cards-wrapper">
                <el-card 
                  v-for="product in vipProducts" 
                  :key="product.productID" 
                  class="product-card"
                  :class="{ 'premium-card': product.price > 100 }"
                >
                  <div class="product-header">
                    <h3>{{ product.name }}</h3>
                    <div class="product-badge" v-if="product.price > 100">推荐</div>
                  </div>
                  <div class="product-description">
                    <p>{{ product.description }}</p>
                  </div>
                  <div class="product-features">
                    <ul>
                      <li>✓ 无限制课程学习</li>
                      <li>✓ 优先客服支持</li>
                      <li>✓ 专属学习资料</li>
                      <li>✓ 学习进度同步</li>
                    </ul>
                  </div>
                  <div class="price">¥{{ product.price }}</div>
                  <el-button 
                    type="primary" 
                    size="large"
                    class="purchase-button"
                    @click="confirmPurchase(product.productID)"
                  >
                    立即购买
                  </el-button>
                </el-card>
              </div>
            </div>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showVipDialog = false">关闭</el-button>
              </span>
            </template>
          </el-dialog>

        </div>
        <div v-else-if="activeTab === 'myCourses'">
          <h2>我的课程</h2>
          <div v-if="loadingMyCourses" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else-if="myCourses.length > 0" class="my-courses-grid">
            <el-card 
              v-for="course in myCourses" 
              :key="course.courseID" 
              class="my-course-card"
              @click="goToCourseDetail(course.courseID)"
            >
              <div class="course-card-content">
                <img :src="course.img" class="course-image" />
                <div class="course-info">
                  <div class="course-title">{{ course.name }}</div>
                  <div class="course-instructor">讲师：{{ course.instructor }}</div>
                  <el-progress :percentage="course.progress" :color="progressColors" />
                  <div class="course-actions">
                    <el-button type="primary" size="small">继续学习</el-button>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
          <el-empty v-else description="暂无课程" />
        </div>
        <div v-else-if="activeTab === 'myCollections'">
          <h2>我的收藏</h2>
          <el-empty description="暂无收藏" />
        </div>
        <div v-else-if="activeTab === 'myOrders'">
          <h2>我的订单</h2>
          <div v-if="loadingMyOrders" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else-if="myOrders.length > 0">
            <el-table :data="myOrders" stripe style="width: 100%">
              <el-table-column prop="orderID" label="订单号" width="220" />
              <el-table-column prop="orderDate" label="下单时间" width="200" />
              <el-table-column prop="productName" label="商品名称" />
              <el-table-column prop="amount" label="订单金额" width="120">
                <template #default="scope">
                  <span>¥{{ scope.row.amount.toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="订单状态" width="120">
                <template #default="scope">
                  <el-tag
                    :type="scope.row.status === '已支付' ? 'success' : (scope.row.status === '已取消' ? 'info' : 'warning')"
                  >
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-empty v-else description="暂无订单" />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '../stores/user.js'
import { getVIPProductList, buyProduct, getMyOrders } from '../api/user.js'
import { getMyCourses } from '../api/course.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Reading, Star, Tickets, User, Message, Stamp, Lock } from '@element-plus/icons-vue'

const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const vipProducts = ref([])
const showVipProducts = ref(false)
const showVipDialog = ref(false)
const activeTab = ref('myCourses')

const myCourses = ref([])
const loadingMyCourses = ref(false)
const myOrders = ref([])
const loadingMyOrders = ref(false)
const progressColors = [
  { color: '#f56c6c', percentage: 30 },
  { color: '#e6a23c', percentage: 70 },
  { color: '#67c23a', percentage: 100 }
]

const fetchMyCourses = async () => {
  loadingMyCourses.value = true
  try {
    const response = await getMyCourses()
    if (response.code === 1) {
      myCourses.value = response.data.items
    } else {
      ElMessage.error(response.message || '获取我的课程失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取我的课程失败')
    console.error('Error fetching my courses:', error)
  } finally {
    loadingMyCourses.value = false
  }
}

const fetchMyOrders = async () => {
  loadingMyOrders.value = true
  try {
    const response = await getMyOrders()
    if (response.code === 1) {
      myOrders.value = response.data.items
    } else {
      ElMessage.error(response.message || '获取我的订单失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取我的订单失败')
    console.error('Error fetching my orders:', error)
  } finally {
    loadingMyOrders.value = false
  }
}

const goToCourseDetail = (courseId) => {
  router.push(`/course/${courseId}`)
}

const fetchVipProducts = async () => {
  try {
    const response = await getVIPProductList()
    if (response.code === 1) {
      vipProducts.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('获取VIP产品列表失败')
    console.error('Error fetching VIP products:', error)
  }
}

const confirmPurchase = async (productID) => {
  // 先确认购买
  try {
    await ElMessageBox.confirm(
      '确定购买此VIP套餐吗？购买后将立即生效。',
      '购买确认',
      {
        confirmButtonText: '确定购买',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true,
        distinguishCancelAndClose: true,
        beforeClose: (action, instance, done) => {
          if (action === 'close') {
            ElMessage.info('购买已取消');
            done();
          } else {
            done();
          }
        }
      }
    );
    
    // 显示加载状态
    const loadingInstance = ElMessage({
      message: '正在处理购买请求...',
      type: 'info',
      duration: 0,
      showClose: false
    });
    
    try {
      const response = await buyProduct(productID);
      loadingInstance.close();
      
      if (response.code === 1) {
        ElMessage.success('购买成功！您的VIP状态已更新');
        // 立即更新用户信息
        await userStore.fetchUserInfo();
        // 关闭购买弹窗
        showVipDialog.value = false;
      } else {
        ElMessage.error(response.message || '购买失败，请重试');
      }
    } catch (error) {
      loadingInstance.close();
      ElMessage.error(error.message || '购买失败，请稍后再试');
      console.error('Error during purchase:', error);
    }
  } catch (error) {
    // 用户取消购买
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('购买操作异常，请重试');
      console.error('Purchase confirmation error:', error);
    }
  }
}

const handleMenuSelect = (index) => {
  activeTab.value = index
  if (index === 'myCourses') {
    fetchMyCourses()
  } else if (index === 'myOrders') {
    fetchMyOrders()
  }
}

const openVipDialog = () => {
  showVipDialog.value = true;
  if (vipProducts.value.length === 0) {
    fetchVipProducts();
  }
};

onMounted(() => {
  const tab = route.query.tab || 'myCourses'
  activeTab.value = tab
  if (tab === 'myCourses') {
    fetchMyCourses()
  } else if (tab === 'myOrders') {
    fetchMyOrders()
  }

  // 如果需要，也可以在这里预加载VIP产品信息
  // fetchVipProducts()
})

// 监听路由变化，以便在同一个页面切换tab
watch(() => route.query.tab, (newTab) => {
  if (newTab) {
    activeTab.value = newTab
    if (newTab === 'myCourses') {
      fetchMyCourses()
    } else if (newTab === 'myOrders') {
      fetchMyOrders()
    }
  }
})

watch(() => userStore.userInfo.isVIP, (newValue) => {
  if (Number(newValue) === 1) {
    showVipDialog.value = false;
    showVipProducts.value = false;
  } else {
    fetchVipProducts();
  }
}, { immediate: true })
</script>

<style scoped>
.user-profile-container {
  width: 95vw;
  display: flex;
  justify-content: center;
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #fdfeff;
}

.profile-aside {
  padding-right: 20px;
}

.el-menu-vertical-demo {
  height: 100%;
}

.profile-main {
  flex-grow: 1;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s ease;
}

.margin-top {
  margin-top: 20px;
}

.cell-item {
  display: flex;
  align-items: center;
}

.cell-item .el-icon {
  margin-right: 5px;
}

.vip-products-container {
  margin-top: 30px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border: 1px solid #eee;
}

.vip-products-container-dialog {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border: 1px solid #eee;
}

.vip-header {
  text-align: center;
  margin-bottom: 30px;
}

.vip-header h2 {
  margin-bottom: 10px;
  color: #333;
  font-size: 24px;
}

.vip-subtitle {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.vip-products-container h2,
.vip-products-container-dialog h2 {
  margin-bottom: 20px;
  text-align: center;
  color: #333;
}

.product-cards-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
}

.product-card {
  width: 280px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-radius: 8px;
  text-align: center;
  padding: 20px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  position: relative;
  overflow: hidden;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.premium-card {
  border: 2px solid #e6a23c;
  background: linear-gradient(135deg, #fff 0%, #fff8e1 100%);
}

.premium-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #e6a23c, #f39c12);
}

.product-header {
  position: relative;
  margin-bottom: 15px;
}

.product-header h3 {
  color: #333;
  margin-bottom: 10px;
  font-size: 1.4em;
  margin: 0;
}

.product-badge {
  position: absolute;
  top: -10px;
  right: -10px;
  background: linear-gradient(45deg, #e6a23c, #f39c12);
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.product-description {
  margin-bottom: 15px;
}

.product-description p {
  color: #666;
  font-size: 0.9em;
  margin: 0;
  min-height: 40px;
  line-height: 1.4;
}

.product-features {
  margin-bottom: 20px;
  text-align: left;
}

.product-features ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.product-features li {
  color: #666;
  font-size: 13px;
  margin-bottom: 8px;
  padding-left: 0;
}

.product-features li::before {
  content: '✓';
  color: #67c23a;
  font-weight: bold;
  margin-right: 8px;
}

.product-card .price {
  font-size: 1.8em;
  color: #e6a23c;
  font-weight: bold;
  margin-bottom: 20px;
}

.purchase-button {
  width: 100%;
  background: linear-gradient(45deg, #409EFF, #66b1ff);
  border: none;
  font-weight: bold;
  transition: all 0.3s ease;
}

.purchase-button:hover {
  background: linear-gradient(45deg, #66b1ff, #409EFF);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.golden-vip .el-descriptions__title {
  color: #e6a23c;
  font-weight: bold;
}

.golden-vip .el-tag--success {
  background-color: #e6a23c;
  border-color: #e6a23c;
  color: #fff;
}

.is-vip-user {
  border: 2px solid #e6a23c;
  box-shadow: 0 0 15px rgba(230, 162, 60, 0.5);
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

/* My Courses Section */
h2 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 10px;
}

.loading-container {
  padding: 20px;
}

.my-courses-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.my-course-card {
  transition: all 0.3s ease;
  cursor: pointer;
}

.my-course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.12);
}

.course-card-content {
  display: flex;
  flex-direction: column;
}

.course-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 4px 4px 0 0;
}

.course-info {
  padding: 16px;
}

.course-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.course-instructor {
  font-size: 14px;
  color: #909399;
  margin-bottom: 12px;
}

.el-progress {
  margin-bottom: 12px;
}

.course-actions {
  display: flex;
  justify-content: flex-end;
}
</style> 